package com.miraclebenelux.ean;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class EANServlet extends HttpServlet {
	
	private boolean checkEAN(String ean)
	{
		return true;
	}
	
	private String wehkampget(String ean)
	{
		String expr = "ArtikelNummer=([^&]+)";
		try {
			int len;
            URL url = new URL("http://www.google.com/search?q=site:wehkamp.nl+EAN+"+ean);
            URLConnection conn =  url.openConnection();
            conn.setRequestProperty("User-Agent",
                            "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.8.1.6) Gecko/20070723 Iceweasel/2.0.0.6 (Debian-2.0.0.6-0etch1)");
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream())
            );
            //String tot="";
            char  tot[] = new char[50000];
            
            len = in.read(tot);
            //while ((str = in.readLine()) != null) {
            //     tot += str;
            //}
            
            String Str = new String(tot);
            
            Pattern patt = Pattern.compile(expr, Pattern.DOTALL | Pattern.UNIX_LINES);
            Matcher m = patt.matcher(Str);
            
            if (m.find())
            {
            	return m.group(1);
            }
            in.close();
            return "";
    }
    catch (MalformedURLException e) {}
    catch (IOException e) {}
    return "";
	}
	
	
	@SuppressWarnings("deprecation")
	private String postURL(String p_url, String var[], String val[], HttpServletResponse resp) 
	{
		String buffer=null;
		String add="";
		URL                 url;
	    URLConnection       urlConn;
	    DataOutputStream    printout;
	    DataInputStream     input;
	    String              content = "";
	    
	    try {
	    // URL of CGI-Bin script.
	    url = new URL (p_url);
	    // URL connection channel.
	    urlConn = url.openConnection();
	    // Let the run-time system (RTS) know that we want input.
	    urlConn.setDoInput (true);
	    // Let the RTS know that we want to do output.
	    urlConn.setDoOutput (true);
	    // No caching, we want the real thing.
	    urlConn.setUseCaches (false);
	    // Specify the content type.
	    urlConn.setRequestProperty
	    ("Content-Type", "application/x-www-form-urlencoded");
	    // Send POST output.
	    printout = new DataOutputStream (urlConn.getOutputStream ());
	    for (int i = 0; i < val.length; i++)
	    {
	    	// resp.getOutputStream().println(var[i] + "="+val[i]);
	    	if (i > 0)
	    	{
	    		add = "&";
	    	}
	    	String enc = URLEncoder.encode(val[i]);
	    	content = content + add + var[i] +"="+enc;
	    }
	    printout.writeBytes (content);
	    printout.flush ();
	    printout.close ();
	    // Get response data.
	    input = new DataInputStream (urlConn.getInputStream ());
	    String str;
	    resp.getOutputStream().println("Receiving....");
	    while (null != ((str = input.readLine())))
	    {
	    	resp.getOutputStream().println("....Line:"+str);
	    	buffer = buffer + str;
	    }

	    input.close ();	
	 } catch (MalformedURLException e) {
         // ...
     	return null;
     } catch (IOException e) {
         // ...
     	return null;
     }	
	    return buffer;	
	}
	
	private String fetchURL(String p_url)
	{
        try {
        	int len;
        	String result = null;
            URL url = new URL(p_url);
            URLConnection connection = url.openConnection();
            
            //BufferedReader in = new BufferedReader(
            //        new InputStreamReader(connection.getInputStream())
            //);
            
            InputStreamReader in =
                 new InputStreamReader(connection.getInputStream());
          
            //String tot="";
            char  tot[] = new char[50000];
            
            len = in.read(tot);
            in.close();
            result = new String(tot);
            return result;
        } catch (MalformedURLException e) {
            // ...
        	return null;
        } catch (IOException e) {
            // ...
        	return null;
        }	
	}
	  private static final String END_OF_INPUT = "\\Z";
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String ean         = req.getParameter("ean");
		String debug       = req.getParameter("debug");
		String expr        = null;
		String expr_search_form = null;
		String val[]       = null;
		String var[]       = null;
		String url         = "";
		String outLine     = "";
		Site WebSites[] =  new Site[8];
		String shop        = req.getParameter("shop");
		String price       = "";
		String site	       = "";
		String outhtml     = "";
		String seq		   = null;
		String pgid        = null;
		String sid         = null;
		String artnr       = "";
		
		if (shop == null)
		{
			shop = "all";
		}

		// Check the EAN
		if (!checkEAN(ean))
		{
			
		}
		
	    url  = "http://www.bol.com/nl/s/algemeen/zoekresultaten/Ntt/PAREAN/Ntk/media_all/Nty/1/N/0/Ne/0/search/true/searchType/qck/index.html?_requestid=44201";
		expr = "<span class=\"price_tag price_tag_bol\">&euro; ([^<]+)";	
		site = "bol.com";
	    WebSites[0] = new Site(expr, url, site, "http://www.bol.com/nl/index.html");
        WebSites[0].Enable();
        
	    url  = "http://www.freerecordshop.nl/is-bin/INTERSHOP.enfinity/WFS/FreeRecordShop-FRS_B2C_NL-Site/nl_NL/-/EUR/ViewFas-Search?action=search&layout=sample1&searchcategory=all&fh_search=PAREAN&x=24&y=10";
	    expr = "\"blauw24\">([^<]+)";
	    site = "frs.nl";
	    WebSites[1] = new Site(expr, url, site, "http://www.freerecordshop.nl");
        WebSites[1].Enable();
        
		url  = "http://www.freerecordshop.be/is-bin/INTERSHOP.enfinity/WFS/FreeRecordShop-FRS_B2C_BE-Site/nl_BE/-/EUR/ViewFas-Search?action=search&layout=sample1&searchcategory=all&fh_search=PAREAN&x=37&y=11";
		expr = "\"blauw24\">([^<]+)";
		site = "frs.be";
		WebSites[2] = new Site(expr, url, site, "http://www.freerecordshop.be");
		WebSites[2].Enable();

		url  = "http://www.vanleest.nl/is-bin/INTERSHOP.enfinity/WFS/FreeRecordShop-VL_B2C_NL-Site/nl_NL/-/EUR/ViewFas-Search;pgid=PARPGID;sid=PARSID=?action=search&layout=sample1&searchcategory=all&fh_search=PAREAN&x=31&y=4";
	    expr = "euro; ([^<]+)";
	    site = "vanleest.nl";
		WebSites[3] = new Site(expr, url, site, "http://www.vanleest.nl");
		WebSites[3].Enable();
//		        http://www.eci.nl/is-bin/INTERSHOP.enfinity/WFS/shop-eci_nl-Site/nl_NL/-/EUR/ViewProductDetail-Start;pgid=GqmRueXc6.E000M3rwv1.2VT0000k-kV8tIT;sid=fJVk99l6gI5tCZJFSdwG0HW77ViUwEi3jKI=?redirectSpecialCase=&Redirected=itemListRedirect&ProductRef=5414233126188
//		        	%40shop-eci_nl&urlparams=fh_search%3d5414233126188%26fh_session%3dfJVk99l6gI5tCZJFSdwG0HW77ViUwEi3jKI%253d%26action%3dsearch%26fh_search_type%3dmus%26fh_usertype%3dnot_logged_in%26fh_secondid%3d5414233126188%26fh_lister_pos%3d0%26fh_location%3d%252f%252froot%252fnl_NL%252f%2524s%253d5414233126188%252fsearchrelevancy%253dsearchrelevancy1%252fassortment%253e%257bnlec%257d%26fh_eds%3d%25c3%259f%26fh_refview%3dsearch&RedirectToDetail=detail&enfaction=detail&Origin=search&CatalogNameL1=&CatalogNameL2=&CatalogNameL3=&ParentCatID=&CategoryL2Flag=true&CategoryL3Flag=&CategoryL4Flag=true&CatalogCategoryID=&CatalogCategoryName=&fh_search=5414233126188&ExtraCategory=false&assortmentID=nlecXtra&assortmentCatName=Boekhandel&FilterSectionsNr=
	    url  = "http://www.eci.nl/is-bin/INTERSHOP.enfinity/WFS/shop-eci_nl-Site/nl_NL/-/EUR/ViewProductDetail-Start;pgid=PARPGID?redirectSpecialCase=&Redirected=itemListRedirect&ProductRef=PAREAN" +
			   "%40shop-eci_nl&urlparams=fh_search%3dPAREAN%3d%26action%3dsearch%26fh_search_type%3dmus%26fh_usertype%3dnot_logged_in%26fh_secondid%3dPAREAN%26fh_lister_pos%3d0%26fh_location%3d%252f%252froot%252fnl_NL%252f%2524s%253dPAREAN%252fsearchrelevancy%253dsearchrelevancy1%252fassortment%253e%257bnlec%257d%26fh_eds%3d%25c3%259f%26fh_refview%3dsearch&RedirectToDetail=detail&enfaction=detail&Origin=search&CatalogNameL1=&CatalogNameL2=&CatalogNameL3=&ParentCatID=&CategoryL2Flag=true&CategoryL3Flag=&CategoryL4Flag=true&CatalogCategoryID=&CatalogCategoryName=&fh_search=PAREAN&ExtraCategory=false&assortmentID=nlecXtra&assortmentCatName=Boekhandel&FilterSectionsNr=";
	    expr = "euro; ([^<]+)";
	    site = "eci.nl";
		WebSites[4] = new Site(expr, url, site, "http://www.eci.nl");
		WebSites[4].Disable();

		url  = "http://www.cosmox.nl/is-bin/INTERSHOP.enfinity/WFS/shop-cosmox_nl-Site/nl_NL/-/EUR/ViewProductDetail-Start;pgid=PARPGID;sid=PARSID=?Redirected=itemListRedirect&ProductRef=PAREAN%40shop-cosmox_nl&urlparams=fh_search%3dPAREAN%26fh_session%3dPARSID%253d%26action%3dsearch%26fh_search_type%3dmus%26fh_usertype%3dnot_logged_in%26fh_secondid%3dPAREAN%26fh_lister_pos%3d0%26fh_location%3d%252f%252froot%252fnl_NL%252f%2524s%253dPAREAN%252fsearchrelevancy%253dsearchrelevancy1%252fassortment%253e%257bnllc%257d%26fh_eds%3d%25c3%259f%26fh_refview%3dsearch&RedirectToDetail=detail&enfaction=detail&Origin=search&CatalogNameL1=&CatalogNameL2=&CatalogNameL3=&ParentCatID=&CategoryL2Flag=true&SearchURLParams=&CatalogCategoryID=&CatalogCategoryName=";
	    expr = "Voor&nbsp;&#8364;([^<]+)";
		site = "cosmox.nl";
		WebSites[5] = new Site(expr, url, site, "http://www.cosmox.nl");
		WebSites[5].Enable();
		
		url  = "http://www.occidentbooks.com/NL/zoek.php?type=cat&categorie=&postingnumbers=0&alfabetisch=&tk=1&catfilter=Prod5&zoeken=PAREAN&x=0&y=0";
		   
		expr = "euro; ([^)]+)";
		//expr = "debug";
		site = "occidentbooks.com";
		WebSites[6] = new Site(expr, url, site, "http://www.occidentbooks.com/NL");
		WebSites[6].Disable();
	
		artnr = wehkampget(ean);
		url = "http://www.wehkamp.nl/Zoeken/Zoeken.aspx?N=186&Nty=1&Ntk=ART&CC=&Ntt="+artnr;
		expr = "class=\"priceTag\">([^<]+)<span>([^<]+)";
		site = "wehkamp.nl";
		WebSites[7] = new Site(expr, url, site, "http://www.wehkamp.nl");
		WebSites[7].Enable();
		
		outhtml = "<TABLE>";
		for (int i=0; i < WebSites.length; i++)
		{
	       if (WebSites[i].expr != null && WebSites[i].enabled)
	       {
	          url = WebSites[i].url;
	          url = url.replaceAll("PAREAN", ean);
	    	  if (req.getParameter("debug") != null)
	    	  {
	             resp.getOutputStream().println(url);
	    	     resp.flushBuffer();
	    	  }

	          if (WebSites[i].sid != null)
	          {
	              url = url.replaceAll("PARSID", WebSites[i].sid);
	          }
	          if (WebSites[i].pgid != null)
	          {
	              url = url.replaceAll("PARPGID", WebSites[i].pgid);
	          }
	          if (WebSites[i].seq != null)
	          {
	              url = url.replaceAll("PARSEQ", WebSites[i].seq);
	          }
	          
	          outhtml += "<TR>";
	    	  if (val != null)
	    	  {
	    		  // Do a post
	    		  outLine = postURL(url, var, val, resp);
	    	  }
	    	  else 
	    	  {
	    		  outLine = fetchURL(url);   
	    		  if (req.getParameter("debug") != null)
	    		  {
	    		     resp.getOutputStream().println(outLine);
	    		  }
	    	  }
	    	  
	    	  if (WebSites[i].expr == "debug")
	    	  {
	    		  resp.getOutputStream().println(outLine);
	    	  }
         	  outhtml += "<TD>";
        	  outhtml += WebSites[i].name;
        	  outhtml += "</TD>";
	    	  if (outLine != null && outLine.length() > 0 && WebSites[i].expr != "debug")
	    	  {
	             Pattern patt = Pattern.compile(WebSites[i].expr, Pattern.DOTALL | Pattern.UNIX_LINES);
	             
	             Matcher m = patt.matcher(outLine);
	            
	             if (m.find())
	             {
	            	 price = m.group(1);
	            	 if (m.groupCount() == 2)
	            	 {
	            		 price += "." + m.group(2);
	            	 }
	            	 outhtml += "<TD>";
	            	 outhtml += price;
	            	 outhtml += "</TD>";
	             }
	             else
	             {
	            	outhtml += "<TD>";
	            	outhtml += "Not Found";
	            	outhtml += "</TD>";
	             }	             
	    	  }
	    	  else
	    	  {
		    	  outhtml += "<TD>";
		          outhtml += "Error";
		          outhtml += "</TD>"; 
	    	  }
	    	  outhtml += "</TR>";
	       }
		}
		outhtml += "</TABLE>";
		resp.getOutputStream().print(outhtml);	
		resp.flushBuffer();
	}
;
}
